package jp.cane.android.luciferblue;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class AuthActivity extends Activity implements OnClickListener {
	final public static String AUTH_USERNAME = "auth_username";
	final public static String AUTH_PASSWORD = "auth_password";

	// final private static String CONFIRM_URL =
	// "http://www.luciferblue.net/member/";
	final private static String CONFIRM_URL = "http://cloudcande.project2108.com/injection/";

	private Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.auth);

		{
			TextView text = (TextView) findViewById(R.id.ID);
			text.setText(MainService.username);
		}

		{
			TextView text = (TextView) findViewById(R.id.password);
			text.setText(MainService.password);
		}

		Button button = (Button) findViewById(R.id.save);
		button.setOnClickListener(this);
	}

	public void onClick(View v) {
		new Thread(new Runnable() {
			public void run() {
				confirm();
			}
		}).start();
	}

	public void confirm() {
		String username = "", password = "";
		{
			TextView text = (TextView) findViewById(R.id.ID);
			username = text.getText().toString();
		}

		{
			TextView text = (TextView) findViewById(R.id.password);
			password = text.getText().toString();
		}

		DefaultHttpClient httpClient = new DefaultHttpClient();

		HttpGet request = new HttpGet(CONFIRM_URL);
		// 認証情報の設定
		UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
				username, password);
		AuthScope scope = new AuthScope(request.getURI().getHost(), request
				.getURI().getPort());
		httpClient.getCredentialsProvider().setCredentials(scope, credentials);

		String result = null;
		try {
			result = httpClient.execute(request, new ResponseHandler<String>() {
				public String handleResponse(HttpResponse response) {
					// response.getStatusLine().getStatusCode()でレスポンスコードを判定する。
					// 正常に通信できた場合、HttpStatus.SC_OK（HTTP 200）となる。
					switch (response.getStatusLine().getStatusCode()) {
					case HttpStatus.SC_OK:
						// レスポンスデータを文字列として取得する。
						// byte[]として読み出したいときはEntityUtils.toByteArray()を使う。
						try {
							return EntityUtils.toString(response.getEntity(),
									"UTF-8");
						} catch (ParseException e) {
						} catch (IOException e) {
						}

					case HttpStatus.SC_NOT_FOUND:
						Log.d("luciferblue", "データないよ！");

					default:
						Log.d("luciferblue", "なんか通信エラーでた");
					}
					return null;
				}
			});
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		// // logcatにレスポンスを表示
		// Log.d("luciferblue", "Result: " + result);

		if (result != null) {
			// 確認が成功したので保存する。
			final String user = username;
			final String pass = password;
			this.handler.post(new Runnable() {
				public void run() {
					save(user, pass);
				}
			});
		} else {
			// 失敗
			this.handler.post(new Runnable() {
				public void run() {
					Toast.makeText(AuthActivity.this, "failed",
							Toast.LENGTH_LONG).show();
				}
			});
		}
	}

	private void save(String username, String password) {
		{
			// 設定値が変更されたので、保存。
			SharedPreferences pref = PreferenceManager
					.getDefaultSharedPreferences(this);
			Editor edit = pref.edit();
			edit.putString(AUTH_USERNAME, username);
			edit.putString(AUTH_PASSWORD, password);
			edit.commit();
		}
		MainService.username = username;
		MainService.password = password;

		finish();
	}
}
